/**
 * 邮件模板预览页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Button,
  Space,
  message,
  Row,
  Col,
  Tag,
  Divider,
  Form,
  Input,
  Spin,
  Alert,
} from 'antd';
import { ArrowLeftOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import {
  getEmailTemplate,
  previewTemplate,
  type TemplatePreviewRequest,
  TemplateType,
  TemplateCategory,
} from '@/services/emailTemplate';

const PreviewEmailTemplate: React.FC = () => {
  const params = useParams();
  const templateId = parseInt(params.id as string);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [template, setTemplate] = useState<any>(null);
  const [previewData, setPreviewData] = useState<any>(null);
  const [variableValues, setVariableValues] = useState<Record<string, string>>({});

  // 获取邮件模板详情
  const fetchEmailTemplate = async () => {
    try {
      const templateData = await getEmailTemplate(templateId);
      setTemplate(templateData);
      
      // 初始化变量值
      const initialValues: Record<string, string> = {};
      templateData.variables?.forEach((variable: string) => {
        initialValues[variable] = `示例${variable}`;
      });
      setVariableValues(initialValues);
      form.setFieldsValue(initialValues);
      
      // 自动生成预览
      await generatePreview(templateData, initialValues);
    } catch (error: any) {
      message.error(error.message || '获取模板详情失败');
      history.push('/templates');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (templateId) {
      fetchEmailTemplate();
    }
  }, [templateId]);

  // 生成预览
  const generatePreview = async (templateData?: any, variables?: Record<string, string>) => {
    const currentTemplate = templateData || template;
    const currentVariables = variables || variableValues;
    
    if (!currentTemplate) return;

    setPreviewLoading(true);
    try {
      const previewRequest: TemplatePreviewRequest = {
        template_id: currentTemplate.id,
        variables: currentVariables,
        template_type: currentTemplate.template_type,
      };

      const result = await previewTemplate(previewRequest);
      setPreviewData(result);
    } catch (error: any) {
      message.error(error.message || '预览生成失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  // 处理变量值变化
  const handleVariableChange = (variable: string, value: string) => {
    const newValues = { ...variableValues, [variable]: value };
    setVariableValues(newValues);
    form.setFieldsValue({ [variable]: value });
  };

  // 重新生成预览
  const handleRefreshPreview = () => {
    generatePreview();
  };

  // 获取模板类型标签
  const getTypeTag = (type: TemplateType) => {
    const typeMap = {
      [TemplateType.HTML]: { color: 'blue', text: 'HTML' },
      [TemplateType.MARKDOWN]: { color: 'green', text: 'Markdown' },
      [TemplateType.PLAIN_TEXT]: { color: 'default', text: '纯文本' },
    };
    const config = typeMap[type] || typeMap[TemplateType.HTML];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取分类标签
  const getCategoryTag = (category: TemplateCategory) => {
    const categoryMap = {
      [TemplateCategory.MARKETING]: { color: 'red', text: '营销邮件' },
      [TemplateCategory.NOTIFICATION]: { color: 'orange', text: '通知邮件' },
      [TemplateCategory.NEWSLETTER]: { color: 'purple', text: '新闻邮件' },
      [TemplateCategory.WELCOME]: { color: 'cyan', text: '欢迎邮件' },
      [TemplateCategory.REMINDER]: { color: 'geekblue', text: '提醒邮件' },
      [TemplateCategory.CUSTOM]: { color: 'default', text: '自定义' },
    };
    const config = categoryMap[category] || categoryMap[TemplateCategory.CUSTOM];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  if (loading) {
    return (
      <PageContainer>
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
          </div>
        </Card>
      </PageContainer>
    );
  }

  if (!template) {
    return (
      <PageContainer>
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Alert message="模板不存在" type="error" />
          </div>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: `预览模板 - ${template.name}`,
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="edit"
          icon={<EditOutlined />}
          onClick={() => history.push(`/templates/edit/${templateId}`)}
        >
          编辑模板
        </Button>,
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/templates')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Row gutter={24}>
        {/* 左侧：模板信息和变量设置 */}
        <Col span={8}>
          <Card title="模板信息" style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8 }}>
              <strong>模板名称：</strong>{template.name}
            </div>
            <div style={{ marginBottom: 8 }}>
              <strong>模板类型：</strong>{getTypeTag(template.template_type)}
            </div>
            <div style={{ marginBottom: 8 }}>
              <strong>分类：</strong>{getCategoryTag(template.category)}
            </div>
            <div style={{ marginBottom: 8 }}>
              <strong>状态：</strong>
              <Tag color={template.is_active ? 'green' : 'red'}>
                {template.is_active ? '启用' : '禁用'}
              </Tag>
            </div>
            {template.description && (
              <div style={{ marginBottom: 8 }}>
                <strong>描述：</strong>{template.description}
              </div>
            )}
            <div>
              <strong>创建时间：</strong>
              {new Date(template.created_at).toLocaleString()}
            </div>
          </Card>

          {template.variables && template.variables.length > 0 && (
            <Card title="变量设置">
              <Form form={form} layout="vertical">
                {template.variables.map((variable: string) => (
                  <Form.Item
                    key={variable}
                    name={variable}
                    label={`{{${variable}}}`}
                  >
                    <Input
                      placeholder={`请输入 ${variable} 的值`}
                      onChange={(e) => handleVariableChange(variable, e.target.value)}
                    />
                  </Form.Item>
                ))}
                <Form.Item>
                  <Button
                    type="primary"
                    icon={<EyeOutlined />}
                    onClick={handleRefreshPreview}
                    loading={previewLoading}
                    block
                  >
                    刷新预览
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          )}
        </Col>

        {/* 右侧：预览效果 */}
        <Col span={16}>
          <Card title="预览效果" loading={previewLoading}>
            {previewData ? (
              <div>
                {/* 邮件主题 */}
                <div style={{ marginBottom: 24 }}>
                  <Divider orientation="left">邮件主题</Divider>
                  <div style={{ 
                    padding: 12, 
                    backgroundColor: '#f5f5f5', 
                    borderRadius: 4,
                    fontSize: 16,
                    fontWeight: 500,
                  }}>
                    {previewData.rendered_subject}
                  </div>
                </div>

                {/* 邮件内容 */}
                <div style={{ marginBottom: 24 }}>
                  <Divider orientation="left">邮件内容</Divider>
                  <div 
                    style={{ 
                      padding: 16, 
                      border: '1px solid #d9d9d9',
                      borderRadius: 4,
                      backgroundColor: '#fff',
                      minHeight: 300,
                    }}
                    dangerouslySetInnerHTML={{ __html: previewData.html_content }}
                  />
                </div>

                {/* 变量使用情况 */}
                {(previewData.variables_used.length > 0 || previewData.missing_variables.length > 0) && (
                  <div>
                    <Divider orientation="left">变量使用情况</Divider>
                    
                    {previewData.variables_used.length > 0 && (
                      <div style={{ marginBottom: 16 }}>
                        <strong>已使用的变量：</strong>
                        <div style={{ marginTop: 8 }}>
                          <Space wrap>
                            {previewData.variables_used.map((variable: string, index: number) => (
                              <Tag key={index} color="green">
                                {variable}
                              </Tag>
                            ))}
                          </Space>
                        </div>
                      </div>
                    )}

                    {previewData.missing_variables.length > 0 && (
                      <div>
                        <strong>缺失的变量：</strong>
                        <div style={{ marginTop: 8 }}>
                          <Space wrap>
                            {previewData.missing_variables.map((variable: string, index: number) => (
                              <Tag key={index} color="red">
                                {variable}
                              </Tag>
                            ))}
                          </Space>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: 50, color: '#999' }}>
                正在生成预览...
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default PreviewEmailTemplate;
